local sys = require "sys"

ADS1115 = {}

IIC_id = 1
ADC_address = 0x48 -- 9.5.1.1，注意:iic是7位地址
--初始化
function ADS1115.init()

    gpio.setup(11, nil, gpio.PULLUP) -- 设置gpio11为输入

    -- 检查i2c1是否存在
    if i2c.exist(1) then
        log.info("存在 i2c1")
    end

    -- 初始化i2c1
    i2c.setup(IIC_id, i2c.FAST) -- 端口正确就一定成功
    -- 如需判断i2c id是否合法, 请使用 i2c.exist 函数

    i2c.send(IIC_id, ADC_address, string.char(0x03, 0x00, 0x00))
    i2c.send(IIC_id, ADC_address, string.char(0x04, 0x80, 0x00)) -- 启动转换就绪引脚9.3.8，其他设置在01寄存中COMP_QUE这个要使能
end
-- MUX：通道选择 0-7
-- FSR：量程选择0-7
-- 这个参数的选择：8.1:噪声性能
function ADS1115.Read_ADC(MUX, FSR)
    a1 = 0x80 + MUX * 16 + FSR * 2 + 1
    if FSR < 0x05 then
        a2 = 0x4 * 32 + 0
    else
        a2 = 0x3 * 32 + 0
    end

    i2c.send(IIC_id, ADC_address, string.char(0x01, a1, a2)) -- 开始转换

    outtime = 1 -- 时间计数器
    sys.wait(1)
    while gpio.get(11) == 0 do -- 当被拉低时转换就绪
        if outtime > 200 then -- 超时处理
            return nil
        end
        outtime = outtime + 1
        sys.wait(1)
    end
    i2c.send(IIC_id, ADC_address, string.char(0x00)) -- 读取值
    local data = i2c.recv(IIC_id, ADC_address, 2) -- ADC的值
    if #data == 0 then -- 通讯失败
        return nil
    end

    num = string.byte(data, 1) * 256 + string.byte(data, 2)
    if num <= 0x8000 then
        num = num - 0x10000
    end
    local ADC = nil
    local switch = {
        [0] = function()
            ADC = num * 0.1875 -- ADC=num/0x8000*6.144
        end,
        [1] = function()
            ADC = num * 0.125 -- ADC=num/0x8000*4.096
        end,
        [2] = function()
            ADC = num * 0.0625 -- ADC=num/0x8000*2.048
        end,
        [3] = function()
            ADC = num * 0.03125 -- ADC=num/0x8000*1.024
        end,
        [4] = function()
            ADC = num * 0.015625 -- ADC=num/0x8000*0.512
        end,
        [5] = function()
            ADC = num * 0.0078125 -- ADC=num/0x8000*0.256
        end,
        [6] = function()
            ADC = num * 0.0078125 -- ADC=num/0x8000*0.256
        end,
        [7] = function()
            ADC = num * 0.0078125 -- ADC=num/0x8000*0.256
        end
    }
    local setUIFunc = switch[FSR]
    if setUIFunc then
        setUIFunc()
    end
    return ADC
end
